package gdconf

import (
	"fmt"
	"server_cluster/common/logger"
	"server_cluster/common/tools"
	"strconv"
	"strings"
)

// 道具配置表

const (
	ITEM_TYPE_ACTIVE      = 1 // 可主动使用道具
	ITEM_TYPE_CURRENCY    = 2 // 货币类
	ITEM_TYPE_EQUIP       = 3 // 装备
	ITEM_TYPE_STUFF       = 4 // 材料道具
	ITEM_TYPE_SPECIAL     = 5 // 特殊道具，单独存储
	ITEM_TYPE_EQUIP_JEWEL = 6 // 装备宝石
	ITEM_TYPE_ROLE        = 7 // 角色
	ITEM_TYPE_WEAPON      = 8 // 武器

	ITEM_EX_TYPE_1 = 1 // 按秒数过期
	ITEM_EX_TYPE_2 = 2 // 按指定日期过期

	ITEM_EXP  = 1
	ITEM_GEM  = 3
	ITEM_GOLD = 4
)

type ItemConfig struct {
	ItemId         int32  `csv:"ID" gorm:"primary_key;autoIncrement:false"` // 道具id
	Type           int32  `csv:"Type,omitempty"`                            // 道具功能类型
	Rarity         int32  `csv:"Rarity,omitempty"`                          // 稀有度
	ExTimeStr      string `csv:"Ex_time,omitempty"`                         // 限时道具时间
	Unique         bool   `csv:"Unique,omitempty"`                          // 是否唯一
	ComposeId      int32  `csv:"Compose,omitempty"`                         // 道具合成id
	AutoUse        bool   `csv:"AutoUse,omitempty"`                         // 自动使用
	ClientNumLimit int32  `csv:"StackingLimit,omitempty"`                   // 客户端堆叠上限

	ExTimeType int8  `gorm:"-" csv:"-"`
	ExTime     int64 `gorm:"-" csv:"-"`
}

func (i *ItemConfig) TableName() string {
	return "config_item"
}

func (g *GameDataConfig) saveItemConfig() {
	saveTableToDb[ItemConfig](g.Db, readTable[ItemConfig](g.CsvPathPrefix+"Item.csv"))
}

func (g *GameDataConfig) loadItemConfig() {
	g.GameDataMaps.ItemConfigMap = make(map[int32]*ItemConfig)
	for _, itemConfig := range loadTableFromDb[ItemConfig](g.Db) {
		if itemConfig.ExTimeStr != "" {
			split := strings.Split(itemConfig.ExTimeStr, "|")
			v1, _ := strconv.Atoi(split[0])
			itemConfig.ExTimeType = int8(v1)
			switch itemConfig.ExTimeType {
			case 1:
				v2, _ := strconv.Atoi(split[1])
				itemConfig.ExTime = int64(v2)
			case 2:
				itemConfig.ExTime = tools.Str2timestamp(split[1])
			default:
				info := fmt.Sprintf("unknown ex time type: %v", itemConfig.ExTimeType)
				panic(info)
			}
		}
		g.GameDataMaps.ItemConfigMap[itemConfig.ItemId] = itemConfig
	}
	logger.Info("ItemConfig Count: %v", len(g.GameDataMaps.ItemConfigMap))
}

func GetItemConfig(itemId int32) *ItemConfig {
	value, exist := CONF.GameDataMaps.ItemConfigMap[itemId]
	if !exist {
		logger.Error("[ConfigNotFound] ItemConfig, itemId: %v", itemId)
		return nil
	}
	return value
}

func GetItemConfigMap() map[int32]*ItemConfig {
	return CONF.GameDataMaps.ItemConfigMap
}
